import Filter from '@src/filter/filter.js'
import RenderCell from 'packages/BaseTableCell/renderCell.js'
import formatColumn from 'packages/BaseTableCell/formatColumn'
import { isUndefined } from '@src/util/type'
import { isOpenData } from '@src/util/platform'
import { getRootWindow } from '@src/util/dom';
import { formatDate } from 'pub-bbx-utils'
import { 
  isNotSupportedDisplayField, 
  isSystemFiled, 
} from '@service/FieldService'

import i18n, { t } from '@src/locales'
/* model */
import { TaskAdvancedAddressFields } from '@src/component/business/BizListView/Impl/BizListViewTask/BizListViewTaskModel'

const SortFieldNames = ['createTime', 'nextTaskCreateTime', 'createdTasks']

const RootWindow = getRootWindow(window)
const isBgiSaas = Boolean(RootWindow.grayAuth?.bgiSaas)

// 高级搜索
/**
 * @return {Array}  
 */
export const getAdvancedFields = (vm) => {
  
  let that = vm;
  
  const bgiSaasArr = isBgiSaas ? [{ // 华大基因字段
    fieldName: 'createRule', // 生成规则
    displayName: i18n.t('task.edit.generateRules.label'),
    formType: 'select',
    setting: {
      isMulti: false, 
      dataSource: [
        {
          text: i18n.t('task.edit.generateRules.all'),
          value: '',
        },
        {
          text: i18n.t('task.edit.generateRules.single'),
          value: 0,
        },
        {
          text: i18n.t('task.edit.generateRules.multiple'),
          value: 1,
        },
      ]
    },
  }] : []

  return [
    {
      displayName: i18n.t('common.task.taskType'),
      fieldName: 'taskType',
      formType: 'select',
      setting: {
        isMulti: false,
        dataSource: that.taskTypeList
      },
    },
    {
      fieldName: 'customer',
      displayName: i18n.t('common.base.customer'),
      formType: 'text',
    },
    {
      isSystem: 1,
      fieldName: 'area',
      isPlanTask: true,
      exportAlias: 'customerAddress',
      displayName: i18n.t('common.fields.area.displayName'),
      formType: 'address',
      defaultValue: null,
      isNull: 1,
      isSearch: 1,
      placeHolder: null,
      setting: {},
      orderId: 1,
      isDelete: 0
    },
    {
      isSystem: 1,
      fieldName: 'planTaskCusAddress',
      isPlanTask: true,
      displayName: i18n.t('common.fields.detailAddress.displayName'),
      formType: 'text',
      defaultValue: null,
      isNull: 1,
      isSearch: 1,
      placeHolder: null,
      setting: {},
      orderId: 1,
      isDelete: 0
    },
    {
      fieldName: 'product',
      displayName: i18n.t('common.base.product'),
      formType: 'text',
    },
    {
      fieldName: 'createUserId',
      displayName: i18n.t('common.base.createUser'),
      formType: 'user',
      defineType: [],
      setting: {
        isMulti: false,
      },
    },
    {
      isSystem: 1,
      fieldName: 'createTime',
      displayName: i18n.t('common.base.createTime'),
      formType: 'datetime',
      orderId: 1,
    },
    {
      fieldName: 'endTime',
      displayName: i18n.t('common.fields.deadline.displayName'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'endTimes',
      displayName: i18n.t('task.list.displayName.executions'),
      formType: 'number',
    },
    {
      fieldName: 'nextCreateTime',
      displayName: i18n.t('common.fields.nextCreateTime.displayName'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'period',
      displayName: i18n.t('common.fields.repetitionPeriod.displayName'),
      formType: 'text',
      setting: {
        isMulti: false, 
        dataSource: [
          i18n.t('common.time.day'),
          i18n.t('common.time.week'),
          i18n.t('common.time.month')
        ]
      }
    },
    {
      fieldName: 'exceptionFlag',
      displayName: i18n.t('task.list.displayName.isExcepted'),
      formType: 'select',
      setting: {
        isMulti: false, 
        dataSource: [
          {
            text: i18n.t('common.base.all'),
            value: '',
          },
          {
            text: i18n.t('common.base.yes'),
            value: 1,
          },
          {
            text: i18n.t('common.base.no'),
            value: 0,
          },
        ]
      },
    },
    ...bgiSaasArr
  ].map(item => {
    return {
      ...item,
      setting: item.setting || {},
      defaultValue: null,
      show: item.show || true,
      isSearch: 1,
      isNull: 1,
      isSystem: 1,
      orderId: 1
    }
  });
}


// 列表 && 选择列
export const getColumnFields = (vm, type) => {
  const that = vm;
  const customerField = that.customerField || {}
  const customerOption = customerField?.setting?.customerOption || {}
  const bgiSaasArr = isBgiSaas ? [{
    fieldName: 'createRule', // 生成规则
    displayName: i18n.t('task.edit.generateRules.label'),
    formType: 'text',
    renderCell(h, col, row) {
      const { createRule } = row
      let generateRules = ''
      if(createRule === 0) {
        generateRules = i18n.t('task.edit.generateRules.single')
      } else if (createRule === 1) {
        generateRules = i18n.t('task.edit.generateRules.multiple')
      }
      return <div>{ generateRules }</div>
    }
  }] : []

  let arr = [];
  if(type && type == 'plan'){
    arr = [
      {
        fieldName: 'planNumber',
        displayName: i18n.t('common.fields.planNumber.displayName'),
        formType: 'text',
        renderCell: (h, col, row) => {
          const planTaskId = row.id || ''
          const name = row.planNumber || ''
          return RenderCell.renderPlanTaskName.call(that, h, name, planTaskId, that.allowViewPlanTaskDetail, isBgiSaas);
        }
      },
    ]
  }
  const fields = [
    ...arr,
    {
      fieldName: 'name',
      displayName: i18n.t('common.fields.taskName.displayName'),
      formType: 'text',
      renderCell: (h, col, row) => {
        const planTaskId = row.id || ''
        const name = row.name || ''
        return RenderCell.renderPlanTaskName.call(that, h, name, planTaskId, that.allowViewPlanTaskDetail, isBgiSaas);
      }
    },
    {
      displayName: i18n.t('common.task.taskType'),
      fieldName: 'templateName',
      formType: 'select',
      renderCell: (h, col, row) => {
        return (
          <div>
            { row?.task?.templateName || '' }
          </div>
        )
      }
    },
    {
      fieldName: 'customer',
      displayName: i18n.t('common.base.customer'),
      formType: 'text',
      renderCell: (h, col, row) => {
        let customer = row?.task?.customer || {}
        let customerName = customer.name || ''
        let customerId = customer.id || ''
        
        return RenderCell.renderCustomer.call(that, h, customerName, customerId, row?.linkAuth)
      }
    },
    {
      fieldName: 'tlmName',
      displayName: i18n.t('common.base.contact'),
      formType: 'select',
      show: customerOption.linkman,
      visibleForSelectColumn: customerOption.linkman,
      renderCell: (h, col, row) => {
        return (
          <div>
            { row?.task?.tlmName || '' }
          </div>
        )
      }
    },
    {
      fieldName: 'tlmPhone',
      displayName: i18n.t('common.base.phone'),
      formType: 'select',
      show: customerOption.linkman,
      visibleForSelectColumn: customerOption.linkman,
      renderCell: (h, col, row) => {
        return (
          <div>
            { row?.task?.tlmPhone || '' }
          </div>
        )
      }
    },
    {
      fieldName: 'taddressStr',
      displayName: i18n.t('common.form.type.customerAddress'),
      formType: 'address',
      show: customerOption.address,
      visibleForSelectColumn: customerOption.address,
      renderCell: (h, col, row) => {
        return (
          <div>
            { Filter.prettyAddress(row?.task?.taddress) }
          </div>
        )
      }
    },
    {
      fieldName: 'products',
      displayName: i18n.t('common.base.product'),
      formType: 'text',
      show: customerOption.product,
      visibleForSelectColumn: customerOption.product,
      renderCell: (h, col, row) => {
        const products = row?.task?.products || []
        return RenderCell.renderProducts(h, products, row?.linkAuth)
      }
    },
    {
      fieldName: 'headName',
      displayName: i18n.t('task.executor'),
      formType: 'user',
      renderCell: (h, col, row) => {
        const { allotSetting = {} } = row
        const { executorName = '', allotType = '', executorStaffId } = allotSetting
        let createUserName = ''
        
        if (allotType == 'normal') {
          createUserName = executorName
        } else if (allotType == 'pool') {
          createUserName = i18n.t('common.task.type.taskPool')
        } else if (allotType == 'auto') {
          createUserName = i18n.t('task.detail.components.autoAllot')
        } else if (allotType == 'waitDistribution') {
          createUserName = i18n.t('task.taskTypes.planTask.toBeAllot')
        }
        if(isOpenData && allotType == 'normal') {
          return <div><open-data type="userName" openid={executorStaffId}></open-data></div>
        }
        return <div>{ createUserName }</div>
      }
    },
    {
      fieldName: 'createUser',
      displayName: i18n.t('common.base.createUser'),
      formType: 'user',
      renderCell: (h, col, row) => {
        const displayName = row.createUserName || ''
        const staffId = row.createUserStaffId || ''
        return <div>{isOpenData ? <open-data type="userName" openid={staffId}></open-data> : displayName}</div>
      }
    },
    {
      fieldName: 'createTime',
      displayName: i18n.t('common.base.createTime'),
      formType: 'datetime',
    },
    {
      fieldName: 'end',
      displayName: i18n.t('common.fields.deadline.displayName'),
      formType: 'datetime',
      sortable: false,
      renderCell(h, col, row) {
        const { endSetting = {} } = row
        const { endBy = '', value = '' } = endSetting
        let endTime = ''
        
        if (endBy == 'times') {
          endTime = i18n.t('task.taskTypes.planTask.executeHowManyTime', {num: value})
        } else {
          endTime = formatDate(value, 'YYYY-MM-DD')
        }
        
        return <div>{ endTime }</div>
      }
    },
    {
      fieldName: 'createdTasks',
      displayName: i18n.t('common.fields.createdTask.displayName'),
      formType: 'text'
    },
    {
      fieldName: 'period',
      displayName: i18n.t('common.fields.repetitionPeriod.displayName'),
      formType: 'text',
      renderCell(h, col, row) {
        const { periodSetting = {} } = row
        const { period = '', periodUnit = '' } = periodSetting
        return <div>{ `${i18n.t('common.base.per')}${period}${periodUnit}` }</div>
      }
    },
    {
      fieldName: 'nextTaskCreateTime',
      displayName: i18n.t('common.fields.nextCreateTime.displayName'),
      formType: 'datetime',
      sortable: true,
    },
    ...bgiSaasArr
  ]

  return fields.map(item => {
    // 初始化属性
    let field = {
      ...item,
      setting: item.setting || {},
      isSystem: 1,
      isNull: 1,
      isSearch: 1,
      orderId: 1,
      show: isUndefined(item.show) ? true : item.show,
      visibleForSelectColumn: isUndefined(item.visibleForSelectColumn) ? true : item.visibleForSelectColumn,
    };
    return formatColumn(field, SortFieldNames, []); 
  })
};

// 任务状态
export const getTaskStatusFields = () => {
  return [
    {
      id: null,
      name: i18n.t('task.list.taskStatus.all'),
    },
    {
      id: 0,
      name: i18n.t('task.list.taskStatus.progress')
    },
    {
      id: 1,
      name: i18n.t('task.list.taskStatus.completed')
    },
    {
      id: 2,
      name: i18n.t('task.list.taskStatus.canceled')
    },
  ]
}